package com.algo.panelmn;

import java.io.IOException;
import java.util.Iterator;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.LongSumReducer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class Method2CookieUVStep4 extends Configured implements Tool {
	public static class Mapper extends org.apache.hadoop.mapreduce.Mapper<Text, Text, Text, DoubleWritable>{
		public void map(Text key, Text value, Context context)
				throws IOException, InterruptedException {
			//output i+uv and corresponding UV weight
			String[] items = ((String)key.toString()).split("\\^");
			long pv = Long.parseLong(items[0]);
			double weight = Double.parseDouble(value.toString());
			for(int i = 1; i <= pv && i <= 10; i++){
				context.write(new Text(items[1] + "," + i + "+"), new DoubleWritable(weight));
				context.write(new Text(items[1] + ",usns," + i + "+"), new DoubleWritable(1));
			}
		}
	}
	public static class Reducer extends org.apache.hadoop.mapreduce.Reducer<Text, DoubleWritable, Text, DoubleWritable>{
		public void reduce(Text key, Iterable<DoubleWritable> values,Context context)
			 throws IOException, InterruptedException {
			double uv = 0;
			Iterator it = values.iterator();
			while(it.hasNext()){
				Double wt = ((DoubleWritable)it.next()).get();
				uv = uv + wt;
			}
			context.write(key, new DoubleWritable(uv));
		}
	}
	
	public static void main(String[] args) throws Exception {
		int res = ToolRunner.run(new Configuration(), new Method2CookieUVStep4(), args);
		System.exit(res);
	}
	public int run(String[] args) throws Exception {
		Configuration conf = getConf();
		Job job = new Job(conf, "Cookie-step4");
		job.setJarByClass(Method2CookieUVStep4.class);
		
		job.setMapperClass(Mapper.class);
		job.setReducerClass(Reducer.class);
		
		job.setInputFormatClass(KeyValueTextInputFormat.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(DoubleWritable.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(DoubleWritable.class);
		
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		if(RunChainJob2.isBatchCaids)   job.setNumReduceTasks(RunChainJob2.step4ReducerNum);
        	else job.setNumReduceTasks(3);
		return job.waitForCompletion(true) ? 0 : 1;
	}
}
